package com.yunjinsuke.recharge.config;

import com.yunjinsuke.recharge.entity.Merchant;
import com.yunjinsuke.recharge.redis.RedisKeyUtil;
import com.yunjinsuke.recharge.redis.RedisUtil;
import com.yunjinsuke.recharge.service.MerchantService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;

@Component
public class GlobalData {


    private final RedisUtil redisUtil;

    private final MerchantService merchantService;

    public GlobalData(MerchantService merchantService, RedisUtil redisUtil) {
        this.merchantService = merchantService;
        this.redisUtil = redisUtil;
    }

    @PostConstruct
    public void init() {
        if (!redisUtil.hasKey(RedisKeyUtil.MERCHANT_INIT_SUCCESS)) {
            redisUtil.set(RedisKeyUtil.MERCHANT_INIT_SUCCESS, true);
            List<Merchant> allMerchantList = merchantService.getAllMerchantList();
            for (Merchant merchant : allMerchantList) {
                redisUtil.set(RedisKeyUtil.appKey(merchant.getAppId()), merchant);
                redisUtil.set(RedisKeyUtil.merchantKey(merchant.getId(), merchant.getMchKey()), null);
            }
        }
    }

    @PreDestroy
    public void destroy() {
    }
}
